package com.evil.common.mongo.service.impl;

import com.evil.common.mongo.entity.LongName;
import com.evil.common.mongo.service.LongService;
import com.evil.common.mongo.service.SequenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

/**
 * 统一封装db操作
 *
 * @author liyang
 * @date 2024-05-23 14:57
 */
@Slf4j
public class LongServiceImpl<M extends MongoRepository<T, Long>, T extends LongName> extends ServiceImpl<Long, M, T> implements LongService<T> {

    @Autowired
    private SequenceService sequenceService;

    @Override
    public String name2Str(Long name) {
        return String.valueOf(name);
    }

    @Override
    public void init(String suffix) {
        List<T> ts = this.readJsonFile(suffix);

        repository.deleteAll();
        String entityName = this.getEntityName();
        sequenceService.clear(entityName);
        ts.forEach(t -> t.setName(sequenceService.generate(entityName, name -> this.repository.existsById(name))));
        repository.insert(ts);
    }

    @Override
    public T addAuto(T t) {
        t.setName(sequenceService.generate(this.getEntityName(), name -> this.repository.existsById(name)));
        return super.add(t);
    }
}
